<template>
  <div>
    <el-card shadow="never">
      <el-skeleton :loading="loading" animated>
        <el-row :gutter="16" justify="space-between">
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <div class="flex items-center">
              <el-avatar :src="avatar" :size="70" class="mr-16px">
                <img src="@/assets/imgs/logo.jpg" alt="" />
              </el-avatar>
              <div>
                <div class="text-20px">
                  {{ t('workplace.welcome') }} {{ username }} {{ t('workplace.happyDay') }}
                </div>
                <div class="mt-10px text-14px text-gray-500">
                  {{ formattedDate }}
                </div>
              </div>
            </div>
          </el-col>
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <div class="h-70px flex items-center justify-end lt-sm:mt-10px">
              <div class="px-8px text-right">
                <div class="mb-16px text-18px text-gray-400">{{ t('workplace.cityNum') }}</div>
                <CountTo
                  class="text-20px"
                  :start-val="0"
                  :end-val="totalSate.cityNum"
                  :duration="2600"
                />
              </div>
              <el-divider direction="vertical" />
              <div class="px-8px text-right">
                <div class="mb-16px text-18px text-gray-400">{{ t('workplace.townNum') }}</div>
                <CountTo
                  class="text-20px"
                  :start-val="0"
                  :end-val="totalSate.townNum"
                  :duration="2600"
                />
              </div>
              <el-divider direction="vertical" border-style="dashed" />
              <div class="px-8px text-right">
                <div class="mb-16px text-18px text-gray-400">{{ t('workplace.villageNum') }}</div>
                <CountTo
                  class="text-20px"
                  :start-val="0"
                  :end-val="totalSate.villageNum"
                  :duration="2600"
                />
              </div>
            </div>
          </el-col>
        </el-row>
      </el-skeleton>
    </el-card>
  </div>

  <el-row class="mt-8px" :gutter="20" justify="space-between">
    <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24" class="mb-8px">

      <el-card shadow="never">
        <template #header>
          <div class="h-3 flex justify-between">
            <span>数据展示</span>
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <el-row>
            <el-col
              v-for="(item, index) in projects"
              :key="`card-${index}`"
              :xl="8"
              :lg="8"
              :md="8"
              :sm="24"
              :xs="24"
            >
              <el-card
                shadow="hover"
                class="mr-5px mt-5px cursor-pointer"
                :style="{ backgroundColor: item.color }"
              >
                <div class="flex items-center">
                  <Icon
                    :icon="item.icon"
                    :size="25"
                    class="mr-8px"
                    :style="{ color: item.color }"
                  />
                  <span class="text-22px text-white text-bold" >{{ item.name }}</span>
                </div>
                <div class="mt-16px text-23px text-white text-bold text-center" >{{ t(item.message) }}</div>

              </el-card>
            </el-col>
          </el-row>
        </el-skeleton>
      </el-card>

      <el-card shadow="never" class="mt-8px">
        <el-skeleton :loading="loading" animated>
          <el-row :gutter="20" justify="space-between">
            <ContentWrap>
              <!-- 搜索工作栏 -->
              <el-form
                class="-mb-15px"
                :model="queryParams"
                ref="queryFormRef"
                :inline="true"
                label-width="68px"
              >
                <el-form-item label="县域" prop="areaId">
                  <el-tree-select
                    v-model="queryParams.areaId"
                    :data="areaTree"
                    :props="defaultProps"
                    check-strictly
                    accordion
                    expand-on-click-node
                    default-expand-all
                    clearable
                    class="!w-340px"
                    placeholder="请选择县域"
                  />
                </el-form-item>
                <el-form-item label="银行机构" prop="bankId">
                  <el-tree-select
                    v-model="queryParams.bankId"
                    :data="deptTree"
                    :props="defaultProps"
                    check-strictly
                    default-expand-all
                    clearable
                    node-key="id"
                    class="!w-240px"
                    placeholder="请选择银行机构"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
                  <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
                </el-form-item>
              </el-form>
            </ContentWrap>
          </el-row>
          <el-row :gutter="20" justify="space-between">
            <el-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
              <el-card shadow="hover" class="mb-8px">
                <el-skeleton :loading="loading" animated>
                  <Echart :options="barFamilyNumData" :height="280" />
                </el-skeleton>
              </el-card>
            </el-col>
            <el-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
              <el-card shadow="hover" class="mb-8px">
                <el-skeleton :loading="loading" animated>
                  <Echart :options="barAmountData" :height="280" />
                </el-skeleton>
              </el-card>
            </el-col>
            <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24">
              <el-card shadow="hover" class="mb-8px">
                <el-skeleton :loading="loading" animated>
                  <Echart :options="barBalanceData" :height="280" />
                </el-skeleton>
              </el-card>
            </el-col>
          </el-row>

        </el-skeleton>
      </el-card>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
//import {set} from 'lodash-es'
import {EChartsOption} from 'echarts'
import {useUserStore} from '@/store/modules/user'
import {DataReportApi,} from '@/api/circ/dataReport'
import {AreaApi, AreaVO,} from '@/api/circ/area'
// import { useWatermark } from '@/hooks/web/useWatermark'
import type { Project,  WorkplaceTotal} from './types'
import {barFamilyNum, barAmount, barBalance,} from './echarts-data'
import {defaultProps, handleTree} from "@/utils/tree";
import * as DeptApi from "@/api/system/dept";
import {DeptVO} from "@/api/system/dept";
//import {getIntDictOptions} from "@/utils/dict";
//console.log(barOptions.data);
//console.log(barOptions.series[0]);

defineOptions({ name: 'Index' })

const { t } = useI18n() // 国际化
const userStore = useUserStore()
const loading = ref(true)
const avatar = userStore.getUser.avatar
const username = userStore.getUser.nickname
const areaTree = ref<Tree[]>([]) // 定义县乡村树形结构变量
const areaList = ref<AreaVO[]>([]) // 定义县乡村树形结构变量
const queryFormRef = ref() // 搜索的表单
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  areaId: undefined,
  bankId: undefined,
  deptId: undefined
})

/** 搜索按钮操作 */
const handleQuery = () => {
  console.log(queryParams);
  getBarYearDatatList(queryParams)
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 查询汇总数据列表 */
const getBarYearDatatList = async (queryParams) => {
  loading.value = true
  try {
    const barYearData = await DataReportApi.getBarYearData(queryParams);

    barFamilyNum.xAxis.data = barYearData.map(item => item.year);
    barFamilyNum.series[0].data = barYearData.map(item => item.familyNum);

    barAmount.xAxis.data = barYearData.map(item => item.year);
    barAmount.series[0].data = barYearData.map(item => item.amount);

    barBalance.xAxis.data = barYearData.map(item => item.year);
    barBalance.series[0].data = barYearData.map(item => item.balance);
    //data.map((v) => t(v.name))

  } catch (err) {
    console.error('请求失败:', err);
    throw new Error('获取柱状图表汇总数据失败');
  }finally {
    loading.value = false
  }
}

// 户数、金额、余额柱状图
//const barOptionsData = reactive<EChartsOption>(barOptions) as EChartsOption
const barFamilyNumData = reactive<EChartsOption>(barFamilyNum) as EChartsOption
const barAmountData = reactive<EChartsOption>(barAmount) as EChartsOption
const barBalanceData = reactive<EChartsOption>(barBalance) as EChartsOption


// 获取统计数,创建一个具有响应式的、类型为 WorkplaceTotal 的对象 totalSate，并初始化其属性值。
let totalSate = reactive<WorkplaceTotal>({
  cityNum: 0,
  townNum: 0,
  villageNum: 0
})

const getCount = async () => {
  const data = await AreaApi.getAreaCount()
  //data 中的属性，合并（浅拷贝）到 totalSate 对象中，从而更新它的值
  Object.assign(totalSate, data)
}
let formattedDate = ""  // 定义一个响应式变量来存储格式化后的日期
const getDate = async () => {
  const currentDate = new Date();
  const options = { year: 'numeric', month: 'long', day: 'numeric' };
  formattedDate = currentDate.toLocaleString('zh-CN', options);
}

// 获取项目数
let projects = reactive<Project[]>([])
const getProject = async () => {
  const currentYearCount = await DataReportApi.getCurrentYearCount()
  const data = [
    {
      name: '本年度贷款户数',
      icon: 'simple-icons:springboot',
      message: '0',
      color: '#6DB33F'
    },
    {
      name: '本年度金额（万元）',
      icon: 'ep:element-plus',
      message: '0',
      color: '#409EFF'
    },
    {
      name: '本年度余额（万元）',
      icon: 'icon-park-outline:mall-bag',
      message: '0',
      color: '#ff4d4f'
    }
  ]
  data[0].message = currentYearCount.familyNum.toString()
  data[1].message = currentYearCount.amount.toString()
  data[2].message = currentYearCount.balance.toString()
  //console.log(currentYearCount.familyNum)
  Object.assign(projects, data)
}



//定义页面所有数据方法
const getAllApi = async () => {
  await Promise.all([
    getCount(),
    getProject(),
    getBarYearDatatList(),
    getDate(),
    // 【加载县乡村树】
    getAreaTree()
  ])
}


/** 初始化 **/
const deptList = ref<DeptVO[]>([])
const deptTree = ref<Tree[]>([]) // 树形结构
onMounted(async () => {
  //调用所有方法获取数据
  await getAllApi()

  // 加载部门列表
  const deptParams = reactive(
    {
      type: 3
    }
  )
  deptList.value = await DeptApi.getSimpleDeptListAppApi(deptParams)
  //console.log(deptList.value)
  // 部门树有层级
  deptTree.value = handleTree(deptList.value)
})

/** 获得县乡村树 */
const getAreaTree = async () => {
  areaTree.value = []
  const params = reactive(
    {
      type: 1
    }
  )
  const data = await AreaApi.getAreaListOfType(params)
  areaList.value = data
  // 组装树形结构数据，并为根节点添加一个空的 children 数组, 县/乡/村层级结构
  const root: Tree = { id: 0, name: '所属市县', children: [] }
  root.children = handleTree(data, 'id', 'parentId')
  areaTree.value.push(root)
}

</script>
